package com.voice.core.connection.frame;

import com.voice.core.connection.Connection;
import com.voice.core.utils.BytesUtil;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class DataFrame extends AbstractFrame {

    public DataFrame() {
    }

    public DataFrame(byte[] bytes, int streamId, boolean endStream) {
        this((byte) 0, bytes, streamId, endStream);
    }

    public DataFrame(byte paddingLength, byte[] bytes, int streamId, boolean endStream) {
        this.length = bytes.length + paddingLength + 1;
        this.streamId = streamId;
        this.type = FrameType.data.getType();
        padded(paddingLength != 0);
        endOfStream(endStream);
        ByteBuffer buffer = ByteBuffer.allocate(length + headerLength);
        buffer.put(BytesUtil.intToBytes(length,3));
        buffer.put(type);
        buffer.put(flag);
        buffer.putInt(streamId);
        if (paddingLength != 0) buffer.put(paddingLength);
        buffer.put(bytes);
        if (paddingLength != 0) buffer.put(new byte[paddingLength]);
        this.payload = buffer.array();
    }

    @Override
    public void onFinish(Connection connection) {
        connection.onDataRead(streamId, getData(), endOfStream());
    }

    @Override
    public byte[] getData() {
        if (padded()) return Arrays.copyOfRange(payload, headerLength + 1, payload.length-getPaddingLength());
        return super.getData();
    }
}
